﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AutoDb {
	/// <summary>
	/// 
	/// </summary>
	sealed class DbModule : DbObject {
		/// <summary>
		/// 
		/// </summary>
		public const string PackageSeperator = ".";

		/// <summary>
		/// 
		/// </summary>
		public string Package { get; set; }

		/// <summary>
		/// 
		/// </summary>
		public string Name { get; set; }

		/// <summary>
		/// 
		/// </summary>
		public IList<DbTable> Tables { get; private set; }

		/// <summary>
		/// 
		/// </summary>
		public IList<DbStatement> Statements { get; private set; }

		/// <summary>
		/// Combine parent package and package.
		/// </summary>
		/// <param name="parent"></param>
		/// <param name="name"></param>
		/// <returns></returns>
		public static string MakeFullPackage(string parent, string name) {
			if (!string.IsNullOrWhiteSpace(parent)) {
				if (!string.IsNullOrWhiteSpace(name)) {
					return parent + PackageSeperator + name;
				} else {
					return parent;
				}
			} else {
				if (!string.IsNullOrWhiteSpace(name)) {
					return name;
				} else {
					System.Diagnostics.Debug.Assert(false, "Argument \"parent\" and \"name\" cannot be null both!");

					return string.Empty;
				}
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="modules"></param>
		/// <returns></returns>
		public static DbModule Merge(params DbModule[] modules) {
			if (modules == null || modules.Length == 0) {
				return null;
			}

			var r = new DbModule(modules[0].LineInfo);
			r.Package = modules[0].Package;
			r.Name = modules[0].Name;
			r.Description = modules[0].Description;

			foreach (var m in modules) {
				foreach (var t in m.Tables) {
					r.Tables.Add(t);
				}

				foreach (var s in m.Statements) {
					r.Statements.Add(s);
				}
			}

			return r;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="lineInfo"></param>
		public DbModule(string lineInfo)
			: base(lineInfo) {
			Tables = new List<DbTable>();
			Statements = new List<DbStatement>();
		}
	} // end of Module.
}
